<template>
  <view class="chat-container" :class="responsiveClass" :style="getContainerStyle('lg')">
    <!-- 侧边面板 -->
    <view class="sidebar" :class="{ 'sidebar-open': showSidebar }">
      <view class="sidebar-header">
        <view class="sidebar-logo">
          <text class="sidebar-logo-icon">⚡</text>
          <text class="sidebar-logo-text">QuickMind</text>
        </view>
        <button class="sidebar-close" @click="toggleSidebar">✕</button>
      </view>
      
      <view class="sidebar-content">
        <button class="new-chat-btn" @click="startNewChat">
          <text class="new-chat-icon">+</text>
          <text class="new-chat-text">新建对话</text>
          <text class="new-chat-shortcut">Ctrl + X</text>
        </button>
        
                  <view class="sidebar-menu">
            <view class="menu-item" @click="goToHistory">
              <text class="menu-icon">🕒</text>
              <text class="menu-text">历史对话</text>
            </view>
            
            <!-- 刷新历史对话按钮 -->
            <view class="menu-item refresh-btn" @click="refreshHistoryChats" :class="{ 'refreshing': isLoadingHistory }">
              <text class="menu-icon">🔄</text>
              <text class="menu-text">{{ isLoadingHistory ? '刷新中...' : '刷新对话' }}</text>
            </view>
            
            
          
          <!-- 历史对话列表 -->
          <view class="history-list">
            
            <!-- 加载状态 -->
            <view v-if="isLoadingHistory" class="history-loading">
              <view class="loading-spinner"></view>
              <text class="loading-text">加载中...</text>
            </view>
            
            <!-- 空状态 -->
            <view v-else-if="historyChats.length === 0" class="history-empty">
              <text class="empty-text">暂无历史对话</text>
            </view>
            
            <!-- 历史对话列表 -->
            <view v-else class="history-item" v-for="(item, index) in historyChats" :key="index">
              <view class="history-item-content" @click="openHistoryChat(item)">
                <text class="history-icon">💬</text>
                <view class="history-content">
                  <text class="history-title">{{ item.title }}</text>
                  <view class="history-details">
                    <text class="history-message-count" v-if="item.messageCount > 0">{{ item.messageCount }}条消息</text>
                    <text class="history-time">{{ item.time }}</text>
                  </view>
                </view>
              </view>
              <view class="history-item-actions">
                <button class="edit-btn" @click.stop="editHistoryChat(item, index)" :disabled="isEditingChat === item.id">
                  <text class="edit-icon">✏️</text>
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部个人信息 -->
      <view class="sidebar-footer">
        <view class="menu-item" @click="goToProfile">
          <text class="menu-icon">👤</text>
          <text class="menu-text">个人信息</text>
        </view>
      </view>
    </view>
    
    <!-- 遮罩层 -->
    <view class="overlay" :class="{ 'overlay-show': showSidebar }" @click="toggleSidebar"></view>

    <!-- H5/APP模式：顶部导航 -->
    <view v-if="showNavbar" class="header">
      <view class="header-left">
        <text class="menu-icon" @click="toggleSidebar">☰</text>
      </view>
      <view class="header-center">
        <text class="app-name">QuickMind</text>
      </view>
      <view class="header-right">
        <text class="share-icon" @click="shareChat">⋯</text>
      </view>
    </view>

    <!-- 小程序模式：顶部状态栏 -->
    <view v-if="!showNavbar" class="mp-header">
      <view class="mp-status-bar">
      </view>
      <view class="mp-nav">
        <text class="mp-menu" @click="toggleSidebar">☰</text>
        <text class="mp-title">QuickMind</text>
        <text class="mp-more" @click="shareChat">⋯</text>
      </view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      :class="{ 'chat-messages-mp': !showNavbar }"
      scroll-y="true" 
      :scroll-top="scrollTop"
      :scroll-into-view="lastMessageId"
      :scroll-with-animation="false"
      :enhanced="true"
      :bounces="false"
      :lower-threshold="50"
      @scroll="onScroll"
      @scrolltolower="scrollToBottom"
      ref="scrollViewRef"
    >
      <view v-for="(msg, idx) in messages" :key="msg.id" :id="msg.id" class="message-item" :class="msg.role === 'assistant' ? 'message-left' : 'message-right'">
        <view v-if="msg.role === 'assistant'" class="message-avatar">
          <text class="avatar-icon">⚡</text>
        </view>
        <view class="message-content">
          <!-- AI思考指示器（省略号） -->
          <view v-if="msg.thinking" class="thinking-indicator">
            <view class="thinking-dots">
              <text class="dot">.</text>
              <text class="dot">.</text>
              <text class="dot">.</text>
            </view>
          </view>
          
          <!-- 正常消息内容 -->
          <view v-else class="message-bubble" :class="{ 'user-bubble': msg.role === 'user' }">
            <text class="message-text">{{ msg.text }}</text>
            <text v-if="msg.role === 'assistant' && msg.typing" class="cursor">▋</text>
          </view>
          <view v-if="msg.role === 'assistant' && !msg.thinking" class="message-actions">
            <text class="action-icon" @click="thumbsDown">👍</text>
            <text class="action-icon" @click="regenerate">🔄</text>
            <text class="action-icon" @click="shareMessage">↗</text>
          </view>
        </view>
      </view>
      
      <!-- 滚动到底部按钮 -->
      <view v-if="showScrollToBottom" class="scroll-to-bottom-btn" @click="scrollToBottom">
        <text class="scroll-icon">↓</text>
      </view>
    </scroll-view>

    <!-- H5/APP模式：底部输入区域 -->
    <view v-if="showNavbar" class="input-bottom-h5">
                <textarea
            class="question-input-h5"
            placeholder="尽管问..."
            v-model="questionText"
            @input="handleInput"
            @keydown="handleKeyDown"
            :disabled="isTyping || isSubmitting"
          ></textarea>
      
      <view class="input-actions-h5">
        <view class="action-left">
          <button class="settings-btn" @click="toggleAdvancedSettings">⚙️</button>
        </view>
        
        <view class="action-right">
          <picker mode="selector" :range="modelOptions.map(m=>m.label)" :value="selectedModelIndex" @change="onModelChange" :disabled="isTyping || isSubmitting">
            <view class="model-selector" :class="{ 'disabled': isTyping || isSubmitting }">
              <text class="model-text">{{ selectedModelLabel }}</text>
              <text class="model-arrow">▼</text>
            </view>
          </picker>
          <button class="deep-thinking-toggle" :class="{ active: isDeepMode }" @click="toggleDeepMode" :disabled="isTyping || isSubmitting">
            <text class="toggle-text">{{ isDeepMode ? '深度思考' : '普通模式' }}</text>
          </button>
          
          <button class="send-btn" @click="sendQuestion" :disabled="isTyping || isSubmitting || !questionText.trim()">
            <text class="send-icon">↑</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 小程序模式：底部输入区域 -->
    <view v-if="!showNavbar" class="input-bottom-mp">
      <textarea 
        class="question-input-bottom" 
        placeholder="尽管问..." 
        v-model="questionText"
        @input="handleInput"
        @keydown="handleKeyDown"
        :disabled="isTyping || isSubmitting"
      ></textarea>
      
      <view class="input-actions-bottom">
        <view class="action-left">
          <button class="settings-btn" @click="toggleAdvancedSettings">⚙️</button>
        </view>
        <view class="action-right">
          <picker mode="selector" :range="modelOptions.map(m=>m.label)" :value="selectedModelIndex" @change="onModelChange" :disabled="isTyping || isSubmitting">
            <view class="model-selector" :class="{ 'disabled': isTyping || isSubmitting }">
              <text class="model-text">{{ selectedModelLabel }}</text>
              <text class="model-arrow">▼</text>
            </view>
          </picker>
          <button class="deep-thinking-toggle" :class="{ active: isDeepMode }" @click="toggleDeepMode" :disabled="isTyping || isSubmitting">
            <text class="toggle-text">{{ isDeepMode ? '深度思考' : '普通模式' }}</text>
          </button>
          
      
          <button class="send-btn" @click="sendQuestion" :disabled="isTyping || isSubmitting || !questionText.trim()">
            <text class="send-icon">↑</text>
          </button>
        </view>
      </view>
    </view>
    
    <!-- 高级设置面板 -->
    <view v-if="showAdvancedSettings" class="advanced-settings">
      <view class="settings-header">
        <text class="settings-title">高级设置</text>
        <text class="settings-close" @click="toggleAdvancedSettings">✕</text>
      </view>
      <view class="settings-content">
        <view class="setting-item">
          <text class="setting-label">Temperature ({{ temperature }})</text>
          <slider 
            :value="temperature * 100" 
            @change="onTemperatureChange" 
            min="0" 
            max="100" 
            step="5"
            activeColor="#667eea"
            backgroundColor="#e9ecef"
          />
        </view>
        <view class="setting-item">
          <text class="setting-label">Max Tokens ({{ maxTokens }})</text>
          <slider 
            :value="maxTokens" 
            @change="onMaxTokensChange" 
            min="500" 
            max="3000" 
            step="100"
            activeColor="#667eea"
            backgroundColor="#e9ecef"
          />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { generateAnswer, getUserConversations, getSessionDetail } from '@/api/qa.js'
import { updateSession } from '@/api/history.js'
import { updateSessionTitle, getLast7DaysRange } from '@/api/history.js'
import { askAI, handleAIError } from '@/api/ai.js'
import { useChatStore } from '../../store/chat.js'
import { showTestButtons, runFullTest } from '@/utils/test-helper.js'
import { registerCleanupCommands } from '@/utils/cleanup-helper.js'
import { registerPlatformCommands } from '@/utils/platform-helper.js'
import { registerNavigationCommands } from '@/utils/navigation-helper.js'
// 响应式相关的计算属性
const responsiveClass = computed(() => {
  // 简单的响应式类，可以根据需要扩展
  return 'device-desktop orientation-portrait'
})

const getContainerStyle = (type = 'lg') => {
  const baseStyle = { width: '100%', maxWidth: '100%', margin: '0 auto', padding: '0 20rpx' }
  const containerWidths = { sm: '540px', md: '720px', lg: '960px', xl: '1140px' }
  return { ...baseStyle, maxWidth: containerWidths[type] || containerWidths.lg, padding: '0 32rpx' }
}

// 响应式数据
const messageText = ref('')
const bottomMessageText = ref('')
  const scrollTop = ref(0)
const showScrollToBottom = ref(false)
const lastScrollPosition = ref(0)
const scrollCheckTimer = ref(null)
const lastMessageHeight = ref(0)
const scrollViewRef = ref(null)

// 计算最后一个消息的ID，用于scroll-into-view
const lastMessageId = computed(() => {
  if (messages.value.length === 0) return ''
  return messages.value[messages.value.length - 1].id
})
  
    // 滚动到底部的函数
  const scrollToBottom = () => {
    nextTick(() => {
      // 清除之前的定时器
      if (scrollCheckTimer.value) {
        clearTimeout(scrollCheckTimer.value)
      }
      
      console.log('执行滚动到底部操作')
      
      // 强制滚动到底部，确保新消息可见
      
      // 小程序端使用不同的滚动策略
      if (!showNavbar.value) {
              // 小程序端：使用更稳定的滚动策略
      console.log('小程序端滚动处理')
      
      // 使用scroll-into-view方法
      if (lastMessageId.value) {
        console.log('使用scroll-into-view滚动到消息:', lastMessageId.value)
      }
      
      // 小程序端：使用更温和的滚动策略，避免跳动
      scrollTop.value = 0
      
      // 小程序端：使用更大的滚动值确保滚动到底部
      scrollTop.value = 999999
      
      setTimeout(() => {
        try {
          const query = uni.createSelectorQuery()
          query.select('.chat-messages').boundingClientRect((rect) => {
            if (rect) {
              console.log('小程序端获取到容器高度:', rect.height)
              // 使用更大的滚动值确保滚动到底部
              scrollTop.value = Math.max(rect.height * 3, 500000)
            }
          }).exec()
        } catch (error) {
          console.warn('小程序端获取容器高度失败:', error)
        }
      }, 50)
      } else {
        // H5/APP端：使用大值滚动
        console.log('H5/APP端滚动处理')
        scrollTop.value = 9999999
      }
      
      showScrollToBottom.value = false
      
      // 根据平台使用不同的滚动值
      const getScrollValue = () => {
        return !showNavbar.value ? 999999 : 9999999
      }
      
      // 根据平台使用不同的滚动策略
      if (!showNavbar.value) {
        // 小程序端：使用多次滚动确保效果
        setTimeout(() => {
          scrollTop.value = getScrollValue()
        }, 10)
        
        setTimeout(() => {
          scrollTop.value = getScrollValue()
        }, 50)
        
        setTimeout(() => {
          scrollTop.value = getScrollValue()
        }, 100)
      } else {
        // H5/APP端：使用多次滚动确保效果
        setTimeout(() => {
          scrollTop.value = getScrollValue()
        }, 1)
        
        setTimeout(() => {
          scrollTop.value = getScrollValue()
        }, 5)
        
        setTimeout(() => {
          scrollTop.value = getScrollValue()
        }, 10)
        
        setTimeout(() => {
          scrollTop.value = getScrollValue()
        }, 20)
        
        // 使用更多的延迟，确保屏幕高度正确调整
        const delays = [50, 100, 150, 200, 300, 500]
        delays.forEach(delay => {
          setTimeout(() => {
            scrollTop.value = getScrollValue()
          }, delay)
        })
      }
      
      // 使用 requestAnimationFrame 确保在下一帧渲染后滚动（仅H5/APP端）
      if (showNavbar.value && typeof requestAnimationFrame !== 'undefined') {
        try {
          requestAnimationFrame(() => {
            scrollTop.value = 999999
          })
        } catch (error) {
          console.warn('requestAnimationFrame 不可用:', error)
        }
      }
      
      // 使用scrollViewRef直接滚动
      setTimeout(() => {
        try {
          if (scrollViewRef.value) {
            // 使用uni-app的scroll-view方法
            const query = uni.createSelectorQuery().in(scrollViewRef.value)
            query.select('.chat-messages').boundingClientRect((rect) => {
              if (rect) {
                scrollTop.value = rect.height * 2
              }
            }).exec()
          }
        } catch (error) {
          console.warn('scrollViewRef滚动方法不可用:', error)
        }
      }, 100)
      
      // 小程序端不使用document相关方法
      if (showNavbar.value) {
        // 只在H5/APP端使用原生滚动方法
        setTimeout(() => {
          try {
            const scrollView = document.querySelector('.chat-messages')
            if (scrollView) {
              scrollView.scrollTop = scrollView.scrollHeight
            }
          } catch (error) {
            console.warn('原生滚动方法不可用:', error)
          }
        }, 150)
      }
    })
  }

  // 滚动到顶部的函数
  const scrollToTop = () => {
    nextTick(() => {
      console.log('执行滚动到顶部操作')
      
      // 小程序端和H5/APP端都使用相同的策略
      scrollTop.value = 0
      
      // 使用多次滚动确保效果
      setTimeout(() => {
        scrollTop.value = 0
      }, 10)
      
      setTimeout(() => {
        scrollTop.value = 0
      }, 50)
      
      setTimeout(() => {
        scrollTop.value = 0
      }, 100)
      
      console.log('滚动到顶部完成')
    })
  }

// 检查消息是否被遮住
const isMessageHidden = () => {
  // 小程序端不使用document相关方法
  if (!showNavbar.value) {
    return false // 小程序端默认认为消息可见
  }
  
  try {
    const messagesContainer = document.querySelector('.chat-messages')
    if (!messagesContainer) return false
    
    const lastMessage = messagesContainer.lastElementChild
    if (!lastMessage) return false
    
    const containerRect = messagesContainer.getBoundingClientRect()
    const messageRect = lastMessage.getBoundingClientRect()
    
    // 检查最后一条消息是否完全可见，留出更多空间
    const isFullyVisible = (
      messageRect.top >= containerRect.top + 20 &&
      messageRect.bottom <= containerRect.bottom - 50
    )
    
    // 检查消息是否被部分遮住
    const isPartiallyHidden = (
      messageRect.bottom > containerRect.bottom - 50 ||
      messageRect.top < containerRect.top + 20
    )
    
    // 如果消息底部距离容器底部太近，也认为被遮住
    const isTooCloseToBottom = (containerRect.bottom - messageRect.bottom) < 50
    
    return !isFullyVisible || isPartiallyHidden || isTooCloseToBottom
  } catch (error) {
    console.warn('检查消息可见性失败:', error)
    return false
  }
}

// 滚动事件处理
const onScroll = (e) => {
  try {
    const currentScrollTop = e.detail.scrollTop
    const scrollHeight = e.detail.scrollHeight
    const clientHeight = e.detail.clientHeight
    
    // 记录当前滚动位置
    lastScrollPosition.value = currentScrollTop
    
    // 检查是否接近底部（距离底部50px以内）
    const isNearBottom = (scrollHeight - currentScrollTop - clientHeight) <= 50
    
    // 如果距离底部超过100px，显示滚动按钮
    showScrollToBottom.value = (scrollHeight - currentScrollTop - clientHeight) > 100
    
    // 清除之前的定时器
    if (scrollCheckTimer.value) {
      clearTimeout(scrollCheckTimer.value)
    }
    
    // 检查消息是否被遮住
    const messageHidden = isMessageHidden()
    
    // 如果正在打字，立即滚动到底部
    if (isTyping.value) {
      console.log('正在打字，立即滚动到底部')
      scrollToBottom()
      
      // 设置备用定时器，确保滚动生效
      scrollCheckTimer.value = setTimeout(() => {
        scrollToBottom()
      }, 200)
    }
    
    console.log('Scroll position:', currentScrollTop, 'isNearBottom:', isNearBottom, 'messageHidden:', messageHidden)
  } catch (error) {
    console.warn('滚动事件处理错误:', error)
  }
}
const questionText = ref('')

const messages = ref([])

// 监听消息变化，强制滚动到底部
watch(messages, () => {
  nextTick(() => {
    // 立即滚动，确保新消息可见
    console.log('消息变化，立即滚动到底部')
    
    // 根据平台设置滚动位置
    const getScrollValue = () => {
      return !showNavbar.value ? 999999 : 9999999
    }
    
    // 强制设置滚动位置
    scrollTop.value = getScrollValue()
    
    // 立即调用滚动函数
    scrollToBottom()
    
    // 根据平台使用不同的滚动策略
    if (!showNavbar.value) {
      // 小程序端：使用多次滚动确保效果
      setTimeout(() => {
        scrollToBottom()
      }, 50)
      
      setTimeout(() => {
        scrollToBottom()
      }, 150)
      
      setTimeout(() => {
        scrollToBottom()
      }, 300)
    } else {
      // H5/APP端：保持原有滚动频率
      setTimeout(() => {
        scrollTop.value = getScrollValue()
        scrollToBottom()
      }, 10)
      
      setTimeout(() => {
        scrollTop.value = getScrollValue()
        scrollToBottom()
      }, 25)
      
      setTimeout(() => {
        scrollTop.value = getScrollValue()
        scrollToBottom()
      }, 50)
      
      setTimeout(() => {
        scrollTop.value = getScrollValue()
        scrollToBottom()
      }, 100)
      
      setTimeout(() => {
        scrollTop.value = getScrollValue()
        scrollToBottom()
      }, 200)
      
      // 最终检查，确保屏幕高度完全调整
      setTimeout(() => {
        console.log('消息变化后最终高度调整检查')
        scrollTop.value = getScrollValue()
        scrollToBottom()
      }, 500)
    }
  })
}, { deep: true })

const isTyping = ref(false)
const isSubmitting = ref(false) // 新增：防止重复提交的标志
const typeSpeedMs = 50
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))
const currentSessionId = ref('')

// 侧边栏控制
const showSidebar = ref(false)

// 历史对话数据
const historyChats = ref([])
const isLoadingHistory = ref(false)
const isEditingChat = ref(null) // 正在编辑的对话ID
const editingTitle = ref('') // 正在编辑的标题

// 使用聊天store
const chatStore = computed(() => {
  try {
    return useChatStore()
  } catch (error) {
    console.error('初始化聊天store失败:', error)
    return null
  }
})

// 获取最近5条对话
const recentChats = computed(() => {
  if (!chatStore.value) return []
  // 确保响应式更新，限制最大数量为5
  const history = chatStore.value.getSortedChatHistory
  return history.slice(0, 5)
})

// 获取当前对话ID
const currentChatId = computed(() => {
  if (!chatStore.value) return null
  return chatStore.value.currentChatId
})

// 检查是否有历史对话
const hasHistory = computed(() => {
  return recentChats.value.length > 0
})

// 模型选择（DeepSeek / 星火V2）
const modelOptions = ref([
  { label: 'DeepSeek', value: 'deepseek', type: 'deepseek', extra: { mode: 'chat' } },
  { label: '星火V2', value: 'x1', type: 'xunfei', extra: { mode: 'chat' } },
])
const selectedModelIndex = ref(0) // 默认选择 DeepSeek
const xunfeiModeOptions = ref([
  { label: '普通模式', value: 'chat' },
  { label: '深度模式', value: 'reasoner' }
])
const xunfeiModeIndex = ref(0)

// 处理从URL传入的模型参数
const handleModelFromUrl = (modelLabel, modelIndex) => {
  console.log('处理URL模型参数:', modelLabel, modelIndex)
  
  // 根据模型标签找到对应的索引
  const modelIndexFromLabel = modelOptions.value.findIndex(m => m.label === modelLabel)
  if (modelIndexFromLabel !== -1) {
    selectedModelIndex.value = modelIndexFromLabel
    console.log('模型已切换到:', modelLabel, '索引:', modelIndexFromLabel)
  } else if (modelIndex !== undefined && modelIndex >= 0 && modelIndex < modelOptions.value.length) {
    // 如果标签没找到，使用索引
    selectedModelIndex.value = Number(modelIndex)
    console.log('根据索引切换模型:', modelIndex, '标签:', modelOptions.value[modelIndex].label)
  } else {
    console.warn('无效的模型参数:', modelLabel, modelIndex)
  }
}

// 参数控制
const temperature = ref(0.7)
const maxTokens = ref(1500)
const showAdvancedSettings = ref(false)
const isDeepMode = ref(false)

const selectedModelItem = computed(() => {
  const index = selectedModelIndex.value
  if (index >= 0 && index < modelOptions.value.length) {
    return modelOptions.value[index]
  }
  // 如果索引无效，返回第一个可用的模型
  return modelOptions.value[0] || null
})
const selectedModelLabel = computed(() => selectedModelItem.value?.label || '选择模型')

const onModelChange = (e) => {
  const idx = Number(e.detail.value || 0)
  // 确保索引在有效范围内
  if (idx >= 0 && idx < modelOptions.value.length) {
    selectedModelIndex.value = idx
    // 如果切到星火V2或DeepSeek，跟随 xunfeiModeIndex 显示
    if (selectedModelItem.value?.type === 'xunfei') {
      // 同一个 value:x1，根据 xunfeiModeIndex 控制 extra.xunfeiMode
      const mode = xunfeiModeOptions.value[xunfeiModeIndex.value]?.value
      if (mode && selectedModelItem.value?.extra) {
        selectedModelItem.value.extra.xunfeiMode = mode
      }
    } else if (selectedModelItem.value?.type === 'deepseek') {
      // DeepSeek模型，根据 xunfeiModeIndex 控制 extra.deepseekMode
      const mode = xunfeiModeOptions.value[xunfeiModeIndex.value]?.value
      if (mode && selectedModelItem.value?.extra) {
        selectedModelItem.value.extra.deepseekMode = mode
      }
    }
  } else {
    console.warn('无效的模型索引:', idx, '可用模型数量:', modelOptions.value.length)
    // 重置为第一个可用模型
    selectedModelIndex.value = 0
  }
}

const onXfModeChange = (e) => {
  const idx = Number(e.detail.value || 0)
  if (idx >= 0 && idx < xunfeiModeOptions.value.length) {
    xunfeiModeIndex.value = idx
    // 同步按钮状态
    isDeepMode.value = xunfeiModeOptions.value[idx].value === 'reasoner'
    if (selectedModelItem.value?.type === 'xunfei' && selectedModelItem.value?.extra) {
      selectedModelItem.value.extra.xunfeiMode = xunfeiModeOptions.value[idx].value
    } else if (selectedModelItem.value?.type === 'deepseek' && selectedModelItem.value?.extra) {
      selectedModelItem.value.extra.deepseekMode = xunfeiModeOptions.value[idx].value
    }
  } else {
    console.warn('无效的模式索引:', idx, '可用模式数量:', xunfeiModeOptions.value.length)
    xunfeiModeIndex.value = 0
  }
}

const onTemperatureChange = (e) => {
  temperature.value = Number(e.detail.value) / 100
}

const onMaxTokensChange = (e) => {
  maxTokens.value = Number(e.detail.value)
}

const typeWriter = async (fullText) => {
  const id = 'm' + Date.now()
  const assistantMsg = { id, role: 'assistant', text: '', typing: true }
  messages.value.push(assistantMsg)
  await nextTick()
  scrollToBottom()
  
  // isTyping 已经在 sendQuestion 中设置为 true，这里不需要重复设置
  const chars = Array.from(fullText)
  for (let i = 0; i < chars.length; i++) {
    assistantMsg.text += chars[i]
    // 保证在各端触发渲染
    messages.value.splice(messages.value.length - 1, 1, { ...assistantMsg })
    await nextTick()
    
      // 减少滚动频率，避免跳动
  if (i % 5 === 0 || i === chars.length - 1) {
    // 小程序端使用更温和的滚动策略
    if (!showNavbar.value) {
      // 小程序端：每10个字符滚动一次，确保内容可见
      if (i % 10 === 0 || i === chars.length - 1) {
        scrollToBottom()
      }
    } else {
      // H5/APP端：保持原有滚动频率
      const getScrollValue = () => {
        return 9999999
      }
      scrollTop.value = getScrollValue()
      scrollToBottom()
    }
  }
    
    await sleep(typeSpeedMs)
  }
  
  assistantMsg.typing = false
  messages.value.splice(messages.value.length - 1, 1, { ...assistantMsg })
  await nextTick()
  
  // 打字完成后立即滚动，确保消息完全可见
  scrollToBottom()
  
  // 根据平台使用不同的滚动策略
  if (!showNavbar.value) {
    // 小程序端：使用多次滚动确保效果
    setTimeout(() => {
      scrollToBottom()
    }, 50)
    
    setTimeout(() => {
      scrollToBottom()
    }, 150)
    
    setTimeout(() => {
      scrollToBottom()
    }, 300)
  } else {
    // H5/APP端：保持原有滚动频率
    setTimeout(() => {
      scrollToBottom()
    }, 10)
    
    setTimeout(() => {
      scrollToBottom()
    }, 25)
    
    setTimeout(() => {
      scrollToBottom()
    }, 50)
    
    setTimeout(() => {
      scrollToBottom()
    }, 100)
    
    setTimeout(() => {
      scrollToBottom()
    }, 200)
    
    setTimeout(() => {
      scrollToBottom()
    }, 300)
    
    setTimeout(() => {
      scrollToBottom()
    }, 500)
  }
  
  isTyping.value = false
  isSubmitting.value = false
}

// 根据平台控制导航栏显示
const showNavbar = computed(() => {
  // #ifdef H5 || APP-PLUS
  return true // H5和APP显示导航栏
  // #endif
  // #ifdef MP-WEIXIN
  return false // 微信小程序隐藏导航栏
  // #endif
  // #ifndef H5 || APP-PLUS || MP-WEIXIN
  return false // 其他平台默认隐藏
  // #endif
})

// 生命周期
onMounted(() => {
  // 验证模型索引的有效性
  if (selectedModelIndex.value >= modelOptions.value.length) {
    console.warn('模型索引超出范围，重置为0')
    selectedModelIndex.value = 0
  }
  
  if (xunfeiModeIndex.value >= xunfeiModeOptions.value.length) {
    console.warn('星火模式索引超出范围，重置为0')
    xunfeiModeIndex.value = 0
  }
  
  // 加载聊天历史数据
  if (chatStore.value) {
    chatStore.value.loadFromStorage()
    
    // 如果没有当前对话，创建一个新的
    if (!chatStore.value.getCurrentChat) {
      console.log('没有当前对话，创建新对话')
      chatStore.value.createNewChat()
    } else {
      console.log('当前对话已存在:', chatStore.value.getCurrentChat.id)
    }
    
    // 如果需要，从服务器同步历史记录
    setTimeout(() => {
      if (chatStore.value.shouldSync()) {
        chatStore.value.syncFromServer()
      }
    }, 1000)
  }
  
  // 立即滚动到底部
  scrollToBottom()
  
  // 根据平台使用不同的滚动策略
  if (!showNavbar.value) {
    // 小程序端：使用多次滚动确保效果
    setTimeout(() => {
      scrollToBottom()
    }, 50)
    
    setTimeout(() => {
      scrollToBottom()
    }, 150)
    
    setTimeout(() => {
      scrollToBottom()
    }, 300)
  } else {
    // H5/APP端：使用多次滚动确保效果
    setTimeout(() => {
      scrollToBottom()
    }, 100)
    
    setTimeout(() => {
      scrollToBottom()
    }, 300)
  }
  
  // 不再从本地恢复旧的会话ID，避免后端清库后引用到失效的 sessionId
  
  // 加载当前对话的消息
  loadCurrentChatMessages()
  
  // 预加载历史对话数据，确保侧边栏打开时能立即显示
  setTimeout(() => {
    console.log('预加载历史对话数据...')
    loadHistoryChats()
  }, 300)
  
  // 延迟再次加载，确保数据更新
  setTimeout(() => {
    console.log('延迟加载历史对话数据...')
    loadHistoryChats()
  }, 2000)
  
  // 统一参数获取逻辑 - 只在onMounted中调用（不依赖 onLoad）
  // 延迟调用，确保页面渲染完成后尝试获取参数
  setTimeout(() => {
    console.log('检查是否需要获取参数:', { hasProcessedParams: hasProcessedParams, messagesLength: messages.value.length })
    // 无论是否已有消息，只要还未处理过参数，就尝试获取并自动发送
    if (!hasProcessedParams) {
      console.log('开始调用getQuestionParams')
      getQuestionParams()
    } else {
      console.log('跳过参数获取:', { hasProcessedParams, messagesLength: messages.value.length })
    }
  }, 300)
  
  // #ifdef H5
  // H5端额外延迟检查，确保页面完全加载
  setTimeout(() => {
    console.log('H5端延迟检查参数...')
    // 移除重复的参数获取，避免多次自动发送
  }, 2000)
  
  // 开发模式下显示测试按钮和清理工具
  setTimeout(() => {
    showTestButtons()
    registerCleanupCommands()
    registerNavigationCommands()
    if (chatStore.value) {
      registerPlatformCommands(chatStore.value)
    }
  }, 3000)
  // #endif
})

// 加载当前对话的消息
const loadCurrentChatMessages = () => {
  try {
    if (!chatStore.value) {
      console.warn('聊天store未初始化')
      return
    }
    
    const currentChat = chatStore.value.getCurrentChat
    console.log('加载当前对话消息:', currentChat)
    
    if (currentChat && currentChat.messages && currentChat.messages.length > 0) {
      console.log('加载历史消息，数量:', currentChat.messages.length)
      // 将历史消息转换为页面显示格式
      messages.value = currentChat.messages.map(msg => ({
        id: msg.id,
        role: msg.role,
        text: msg.content,
        typing: false
      }))
      
      // 如果有sessionId，恢复它
      if (currentChat.sessionId) {
        currentSessionId.value = currentChat.sessionId
        uni.setStorageSync('qa_session_id', currentChat.sessionId)
        console.log('恢复会话ID:', currentChat.sessionId)
      }
      
      // 加载完历史消息后立即滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
      
      // 根据平台使用不同的滚动策略
      if (!showNavbar.value) {
        // 小程序端：使用多次滚动确保效果
        setTimeout(() => {
          scrollToBottom()
        }, 50)
        
        setTimeout(() => {
          scrollToBottom()
        }, 150)
        
        setTimeout(() => {
          scrollToBottom()
        }, 300)
      } else {
        // H5/APP端：使用多次滚动确保效果
        setTimeout(() => {
          scrollToBottom()
        }, 100)
        
        setTimeout(() => {
          scrollToBottom()
        }, 300)
      }
    } else {
      console.log('当前对话为空或不存在，清空消息列表')
      messages.value = []
    }
  } catch (error) {
    console.error('加载对话消息失败:', error)
  }
}

// 定义 onLoad 函数供页面使用
const onLoad = (options) => {
  console.log('onLoad 被调用，参数:', options)
  
  // 处理模型参数
  if (options && options.model) {
    console.log('检测到模型参数:', options.model)
    handleModelFromUrl(options.model, options.modelIndex)
  }
  
  // 如果有问题参数，立即处理
  if (options && options.question) {
    console.log('onLoad中检测到问题参数:', options.question)
    // 只有在没有历史消息时才自动处理参数
    if (messages.value.length === 0) {
      console.log('没有历史消息，调用参数获取函数')
      getQuestionParams()
    } else {
      console.log('已有历史消息，跳过自动参数处理')
      hasProcessedParams = true
    }
    
    // 延迟清除URL参数，确保问题已经发送
    setTimeout(() => {
      try {
        console.log('准备清除URL参数...')
        // 小程序端：使用redirectTo清除参数
        // #ifdef MP-WEIXIN
        const currentPages = getCurrentPages()
        if (currentPages.length > 0) {
          const currentPage = currentPages[currentPages.length - 1]
          if (currentPage.options && currentPage.options.question) {
            console.log('小程序端清除URL参数')
            // 重新加载页面但不带参数
            uni.redirectTo({
              url: '/pages/Questions/questions'
            })
          }
        }
        // #endif
        
        // H5端：清除URL参数
        // #ifdef H5
        if (window.history && window.history.replaceState) {
          const newUrl = window.location.pathname + window.location.hash.split('?')[0]
          window.history.replaceState({}, document.title, newUrl)
          console.log('H5端清除URL参数')
        }
        // #endif
      } catch (error) {
        console.warn('清除URL参数失败:', error)
      }
    }, 5000) // 5秒后清除，确保问题有足够时间发送
  }
}

// 防止重复执行的标志
let hasProcessedParams = false
// 控制是否允许自动提问的标志
let allowAutoQuestion = true // 默认启用自动提问

// 统一参数获取函数
const getQuestionParams = () => {
  // 防止重复执行
  if (hasProcessedParams) {
    console.log('参数已处理过，跳过重复执行')
    return false
  }
  
  // 检查是否允许自动提问
  if (!allowAutoQuestion) {
    console.log('自动提问已禁用，跳过参数获取')
    hasProcessedParams = true
    return false
  }
  
  // 若已有消息，仍允许检测URL参数并自动发送（来自首页的跳转应优先生效）
  if (messages.value.length > 0) {
    console.log('已有消息存在，但继续检测URL参数以支持自动提问')
  }
  
  console.log('开始获取问题参数...')
  
  // 方法1: 通过 getCurrentPages 获取（小程序端）
  try {
    const pages = getCurrentPages()
    if (pages && pages.length > 0) {
      const currentPage = pages[pages.length - 1]
      const options = currentPage.options || {}
      console.log('getCurrentPages 参数:', options)
      
      // 处理模型参数
      if (options.model) {
        console.log('getCurrentPages 获取到模型参数:', options.model)
        handleModelFromUrl(options.model, options.modelIndex)
      }
      
      if (options.question) {
        const question = decodeURIComponent(options.question)
        console.log('getCurrentPages 获取到问题:', question)
        console.log('设置questionText.value:', question)
        questionText.value = question
        hasProcessedParams = true
        console.log('hasProcessedParams设置为true')
        console.log('准备1.5秒后自动发送问题...')
        setTimeout(() => {
          console.log('=== 开始自动发送问题 ===')
          console.log('当前questionText.value:', questionText.value)
          console.log('调用sendQuestion函数...')
          sendQuestion()
        }, 1500)
        return true
      }
    }
  } catch (error) {
    console.error('getCurrentPages 获取参数失败:', error)
  }
  
  // 方法2: H5端URL参数获取
  // #ifdef H5
  try {
    const currentUrl = window.location.href
    console.log('H5 当前URL:', currentUrl)
    
    // 检查hash路由中的参数
    if (currentUrl.includes('#')) {
      const hashPart = currentUrl.split('#')[1]
      console.log('H5 hash部分:', hashPart)
      
      if (hashPart && hashPart.includes('question=')) {
        const questionMatch = hashPart.match(/question=([^&]+)/)
        if (questionMatch && questionMatch[1]) {
          const question = decodeURIComponent(questionMatch[1])
          console.log('H5 hash中获取到问题:', question)
          questionText.value = question
          hasProcessedParams = true
          setTimeout(() => {
            console.log('H5 hash开始自动发送问题')
            sendQuestion()
          }, 1500)
          return true
        }
      }
    }
    
    // 使用 URLSearchParams (标准查询参数)
    const urlParams = new URLSearchParams(window.location.search)
    const question = urlParams.get('question')
    if (question) {
      console.log('H5 URL参数获取到问题:', question)
      const decodedQuestion = decodeURIComponent(question)
      console.log('H5 解码后问题:', decodedQuestion)
      questionText.value = decodedQuestion
      hasProcessedParams = true
      setTimeout(() => {
        console.log('H5 开始自动发送问题')
        sendQuestion()
      }, 1500)
      return true
    }
    
    // 检查整个URL字符串
    if (currentUrl.includes('question=')) {
      const urlParts = currentUrl.split('question=')
      if (urlParts.length > 1) {
        const questionPart = urlParts[1].split('&')[0]
        const decodedQuestion3 = decodeURIComponent(questionPart)
        console.log('H5 方法3获取到问题:', decodedQuestion3)
        questionText.value = decodedQuestion3
        hasProcessedParams = true
        setTimeout(() => {
          console.log('H5 方法3开始自动发送问题')
          sendQuestion()
        }, 1500)
        return true
      }
    }
    
    // 方法4: 从localStorage获取参数（H5端备用方案）
    try {
      const pendingQuestion = uni.getStorageSync('pending_question')
      if (pendingQuestion) {
        console.log('H5 localStorage获取到问题:', pendingQuestion)
        questionText.value = pendingQuestion
        hasProcessedParams = true
        // 清除localStorage中的问题
        uni.removeStorageSync('pending_question')
        setTimeout(() => {
          console.log('H5 localStorage开始自动发送问题')
          sendQuestion()
        }, 1500)
        return true
      }
    } catch (error) {
      console.error('H5 localStorage获取参数失败:', error)
    }
    
    console.log('H5 所有方法都未获取到参数')
  } catch (error) {
    console.error('H5参数获取失败:', error)
  }
  // #endif
  
  console.log('未获取到任何问题参数')
  return false
}

// 控制自动提问功能
const setAutoQuestionEnabled = (enabled) => {
  allowAutoQuestion = enabled
  console.log('自动提问功能:', enabled ? '已启用' : '已禁用')
}

// 暴露 onLoad 给页面实例
defineExpose({
  onLoad,
  setAutoQuestionEnabled
})

// 侧边栏相关方法
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
  console.log('问答页面侧边栏状态:', showSidebar.value)
  // 当侧边栏打开时，强制刷新历史对话
  if (showSidebar.value) {
    console.log('问答页面侧边栏打开，强制刷新历史对话')
    // 延迟一点时间确保侧边栏动画完成后再加载
    setTimeout(() => {
      loadHistoryChats()
    }, 100)
  }
}

// 新建对话
const startNewChat = () => {
  showSidebar.value = false
  
  if (!chatStore.value) {
    console.error('聊天存储不可用')
    uni.showToast({
      title: '聊天存储初始化失败',
      icon: 'error'
    })
    return
  }
  
  try {
    // 创建新对话
    const newChat = chatStore.value.createNewChat()
    console.log('创建新对话成功:', newChat)
    
    // 清空当前消息列表
    messages.value = []
    
    // 清空输入框
    questionText.value = ''
    
    // 重置会话ID
    currentSessionId.value = null
    uni.removeStorageSync('qa_session_id')
    
    // 加载新对话的消息（应该是空的）
    loadCurrentChatMessages()
    
    // 立即滚动到底部
    scrollToBottom()
    
    // 显示成功提示
    uni.showToast({
      title: '新对话已创建',
      icon: 'success',
      duration: 1500
    })
    
    console.log('新建对话完成，当前对话ID:', currentChatId.value)
  } catch (error) {
    console.error('创建新对话失败:', error)
    uni.showToast({
      title: '创建新对话失败',
      icon: 'error'
    })
  }
}

// 跳转到个人信息页面
const goToProfile = () => {
  showSidebar.value = false
  uni.navigateTo({
    url: '/pages/profile/profile'
  })
}

// 跳转到历史对话页面
const goToHistory = () => {
  showSidebar.value = false
  // 检查页面栈，避免重复跳转
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  
  if (currentPage.route !== 'pages/history/history') {
    console.log('问答页面跳转到历史页面')
  uni.navigateTo({
    url: '/pages/history/history'
  })
  } else {
    console.log('已在历史页面，关闭侧边栏')
  }
}

// 加载历史对话
const loadHistoryChats = async () => {
  try {
    isLoadingHistory.value = true
    console.log('开始加载历史对话...')
    
    // 优先调用真实API获取数据（最近7天 + deepseek-chat 模型 + 前5条）
    try {
      const dateRange = getLast7DaysRange()
      console.log('请求日期范围:', dateRange)
      
      const response = await getUserConversations({
        startDate: dateRange.startDate,
        endDate: dateRange.endDate,
        model: 'deepseek-chat',
        page: 1,
        pageSize: 5
      })

      console.log('历史对话API响应:', response)
      console.log('响应状态码:', response?.statusCode || response?.code)
      console.log('响应数据:', response?.data)

      const conversations = response?.data?.conversations || response?.data?.records || response?.data || []
      console.log('解析的对话数据:', conversations)
      
      if (Array.isArray(conversations) && conversations.length > 0) {
        const mappedConversations = conversations.map((conv, index) => {
          // 尝试从多个字段获取标题
          let title = conv.title || conv.question || conv.topic || conv.sessionTitle || conv.name
          
          // 如果没有标题，尝试从第一条消息生成标题
          if (!title && conv.messages && conv.messages.length > 0) {
            const firstMessage = conv.messages[0]
            if (firstMessage.content && firstMessage.content.length > 0) {
              title = firstMessage.content
            }
          }
          
          // 如果还是没有标题，使用默认标题
          if (!title) {
            title = `对话 ${index + 1}`
          }
          
          // 统一处理标题截断（限制为15个字符，避免在侧边栏中过长）
          title = truncateTitle(title, 15)
          
          return {
            id: conv.id || conv.sessionId || `conv_${index}`,
            title: title,
            originalTitle: conv.title || conv.question || conv.topic || conv.sessionTitle || conv.name || title, // 保存原始标题用于编辑
            time: formatTime(
              conv.createdAt || conv.createTime || conv.timestamp || conv.lastActiveAt || conv.updatedAt || Date.now()
            ),
            lastMessage: conv.lastMessage || conv.answer || conv.preview || conv.summary || '暂无内容',
            sessionId: conv.sessionId || conv.id || null,
            messageCount: conv.messageCount || conv.messages?.length || 0
          }
        })
        
        historyChats.value = mappedConversations.slice(0, 5)
        console.log('成功加载真实历史对话:', historyChats.value)
        console.log('历史对话数量:', historyChats.value.length)
      } else {
        console.log('API无数据，保持为空')
        historyChats.value = []
      }
    } catch (apiError) {
      console.error('加载历史对话API失败:', apiError)
      console.error('错误详情:', {
        message: apiError.message,
        status: apiError.status,
        statusCode: apiError.statusCode,
        data: apiError.data
      })
      historyChats.value = []
      
      // 显示错误提示
      uni.showToast({
        title: '加载历史对话失败',
        icon: 'error',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('加载历史对话失败:', error)
    historyChats.value = []
  } finally {
    isLoadingHistory.value = false
  }
}

// 截断标题文本
const truncateTitle = (title, maxLength = 15) => {
  if (!title || typeof title !== 'string') {
    return '新对话'
  }
  
  // 移除多余的空白字符
  const cleanTitle = title.trim()
  
  if (cleanTitle.length <= maxLength) {
    return cleanTitle
  }
  
  // 截断并添加省略号
  return cleanTitle.substring(0, maxLength) + '...'
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '刚刚'
  
  try {
    const now = new Date()
    const date = new Date(timestamp)
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '刚刚'
    }
    
    const diff = now - date
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚'
    }
    
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (minutes < 60) {
      return `${minutes}分钟前`
    } else if (hours < 24) {
      return `${hours}小时前`
    } else if (days < 7) {
      return `${days}天前`
    } else if (days < 30) {
      return `${Math.floor(days / 7)}周前`
    } else if (days < 365) {
      return `${Math.floor(days / 30)}个月前`
    } else {
      return `${Math.floor(days / 365)}年前`
    }
  } catch (error) {
    console.error('时间格式化失败:', error)
    return '刚刚'
  }
}

// 打开历史对话
const openHistoryChat = async (chat) => {
  showSidebar.value = false
  console.log('打开历史对话:', chat.title)
  
  try {
    // 如果有sessionId，尝试从服务器加载完整对话
    if (chat.sessionId) {
      try {
        // 这里可以调用API获取完整的对话消息
        // const sessionMessages = await getSessionMessages(chat.sessionId)
        // 暂时使用模拟数据
        messages.value = [
          {
            id: 'm' + Date.now() + '-u',
            role: 'user',
            text: chat.title,
            typing: false
          },
          {
            id: 'm' + Date.now() + '-a',
            role: 'assistant',
            text: chat.lastMessage,
            typing: false
          }
        ]
      } catch (apiError) {
        console.warn('获取完整对话失败，使用基本信息:', apiError)
        // API失败时使用基本信息
        messages.value = [
          {
            id: 'm' + Date.now() + '-u',
            role: 'user',
            text: chat.title,
            typing: false
          },
          {
            id: 'm' + Date.now() + '-a',
            role: 'assistant',
            text: chat.lastMessage,
            typing: false
          }
        ]
      }
    } else {
      // 没有sessionId，使用基本信息
      messages.value = [
        {
          id: 'm' + Date.now() + '-u',
          role: 'user',
          text: chat.title,
          typing: false
        },
        {
          id: 'm' + Date.now() + '-a',
          role: 'assistant',
          text: chat.lastMessage,
          typing: false
        }
      ]
    }
    
    // 滚动到底部
    scrollToBottom()
    
    uni.showToast({
      title: '已加载历史对话',
      icon: 'success',
      duration: 1500
    })
  } catch (error) {
    console.error('加载历史对话失败:', error)
    uni.showToast({
      title: '加载对话失败',
      icon: 'none'
    })
  }
}

// 删除历史对话
const deleteHistoryChat = async (chat, index) => {
  try {
    // 显示确认对话框
    const res = await uni.showModal({
      title: '确认删除',
      content: `确定要删除对话"${chat.title}"吗？此操作不可恢复。`,
      confirmText: '删除',
      cancelText: '取消',
      confirmColor: '#ff4757'
    })
    
    if (!res.confirm) {
      return
    }
    
    // 设置删除状态
    isDeletingChat.value = chat.id
    
    console.log('删除历史对话:', chat.title, '索引:', index)
    
    // 从本地历史对话列表中移除
    historyChats.value.splice(index, 1)
    
    // 如果使用了store，也从store中删除
    if (chatStore.value && chat.id) {
      chatStore.value.deleteChat(chat.id)
    }
    
    // 尝试从服务器删除（优先使用无需权限接口）
    try {
      if (chat.sessionId) {
        try {
          await deleteSessionNoAuth(chat.sessionId)
          console.log('对话已从服务器删除(无权限接口):', chat.sessionId)
        } catch (e) {
          // 回退到需要权限的接口
          await deleteSession(chat.sessionId)
          console.log('对话已从服务器删除(授权接口):', chat.sessionId)
        }
      } else {
        console.log('对话没有sessionId，跳过服务器删除')
      }
    } catch (apiError) {
      console.warn('服务器删除失败，但本地已删除:', apiError)
      try {
        const serverMsg = apiError?.data?.message || apiError?.message
        if (serverMsg) {
          uni.showToast({ title: serverMsg, icon: 'none' })
        } else {
          uni.showToast({ title: '服务器拒绝删除或参数错误', icon: 'none' })
        }
      } catch (_) {}
    }
    
    // 显示删除成功提示
    uni.showToast({
      title: '对话已删除',
      icon: 'success',
      duration: 1500
    })
    
  } catch (error) {
    console.error('删除历史对话失败:', error)
    uni.showToast({
      title: '删除失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    // 清除删除状态
    isDeletingChat.value = null
  }
}

// 刷新历史对话
const refreshHistoryChats = async () => {
  if (isLoadingHistory.value) {
    return // 防止重复刷新
  }
  
  try {
    console.log('手动刷新历史对话...')
    await loadHistoryChats()
    
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1500
    })
  } catch (error) {
    console.error('刷新历史对话失败:', error)
    uni.showToast({
      title: '刷新失败',
      icon: 'error',
      duration: 2000
    })
  }
}

// 编辑历史对话
const editHistoryChat = async (chat, index) => {
  try {
    // 设置编辑状态
    isEditingChat.value = chat.id
    // 使用原始标题进行编辑，如果没有则使用当前标题
    const editTitle = chat.originalTitle || chat.title
    editingTitle.value = editTitle
    
    // 显示输入对话框
    const res = await uni.showModal({
      title: '修改对话标题',
      content: '请输入新的对话标题',
      editable: true,
      placeholderText: editTitle,
      confirmText: '保存',
      cancelText: '取消',
      confirmColor: '#667eea'
    })
    
    if (!res.confirm || !res.content || res.content.trim() === '') {
      return
    }
    
    const newTitle = res.content.trim()
    
    // 如果标题没有变化，直接返回
    if (newTitle === chat.title) {
      return
    }
    
    console.log('修改对话标题:', chat.title, '->', newTitle)
    
    // 更新本地历史对话列表（保存原始标题和截断后的标题）
    historyChats.value[index].originalTitle = newTitle
    historyChats.value[index].title = truncateTitle(newTitle, 15)
    
    // 如果使用了store，也更新store中的对话标题
    if (chatStore.value && chat.id) {
      chatStore.value.updateChatTitle(chat.id, newTitle)
    }
    
    // 尝试从服务器更新（统一update接口）
    try {
      if (chat.sessionId) {
        await updateSession({
          sessionId: chat.sessionId,
          sessionTitle: newTitle,
          sessionStatus: 'active',
          metadata: JSON.stringify({ source: 'client', ts: Date.now() })
        })
        console.log('对话标题已从服务器更新:', chat.sessionId)
      } else {
        console.log('对话没有sessionId，跳过服务器更新')
      }
    } catch (apiError) {
      console.warn('服务器更新失败，但本地已更新:', apiError)
    }
    
    // 显示更新成功提示
    uni.showToast({
      title: '标题已修改',
      icon: 'success',
      duration: 1500
    })
    
  } catch (error) {
    console.error('修改对话标题失败:', error)
    uni.showToast({
      title: '修改失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    // 清除编辑状态
    isEditingChat.value = null
    editingTitle.value = ''
  }
}

// 切换到指定对话
const switchToChat = (chatId) => {
  if (!chatStore.value) return
  
  // 如果已经是当前对话，只关闭侧边栏
  if (chatId === currentChatId.value) {
    showSidebar.value = false
    return
  }
  
  chatStore.value.switchToChat(chatId)
  showSidebar.value = false
  
  // 加载选中对话的消息
  loadCurrentChatMessages()
  
  // 立即滚动到底部
  scrollToBottom()
  
  // 根据平台使用不同的滚动策略
  if (!showNavbar.value) {
    // 小程序端：使用多次滚动确保效果
    setTimeout(() => {
      scrollToBottom()
    }, 50)
    
    setTimeout(() => {
      scrollToBottom()
    }, 150)
    
    setTimeout(() => {
      scrollToBottom()
    }, 300)
  } else {
    // H5/APP端：使用多次滚动确保效果
    setTimeout(() => {
      scrollToBottom()
    }, 100)
    
    setTimeout(() => {
      scrollToBottom()
    }, 300)
  }
  
  // 显示切换成功提示
  uni.showToast({
    title: '已切换到新对话',
    icon: 'success',
    duration: 1500
  })
}

// 删除指定对话
const deleteChat = (chatId) => {
  if (!chatStore.value) return
  
  // 如果是当前对话，不允许删除
  if (chatId === currentChatId.value) {
    uni.showToast({
      title: '不能删除当前对话',
      icon: 'none'
    })
    return
  }
  
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个对话吗？删除后无法恢复。',
    success: (res) => {
      if (res.confirm) {
        chatStore.value.deleteChat(chatId)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}



// 方法
const goBack = () => {
  // 检查是否可以返回上一页
  const pages = getCurrentPages()
  if (pages.length > 1) {
    // 有上一页，可以返回
    uni.navigateBack()
  } else {
    // 没有上一页，跳转到首页
    uni.reLaunch({
      url: "/pages/index/index"
  })
  }
}
const shareChat = () => {
  uni.showToast({
    title: '分享功能开发中',
    icon: 'none'
  })
}
const thumbsDown = () => {
  uni.showToast({
    title: '已反馈',
    icon: 'success'
  })
}
const regenerate = async () => {
  // 防止重复操作
  if (isTyping.value || isSubmitting.value) {
    console.log('正在处理中，忽略重复操作')
    return
  }
  
  // 找到最后一条AI消息
  const lastAiMessageIndex = messages.value.findLastIndex(msg => msg.role === 'assistant' && !msg.thinking)
  
  if (lastAiMessageIndex === -1) {
    uni.showToast({
      title: '没有可重新生成的消息',
      icon: 'none'
    })
    return
  }
  
  // 找到对应的用户问题
  const userMessageIndex = messages.value.findLastIndex((msg, index) => 
    msg.role === 'user' && index < lastAiMessageIndex
  )
  
  if (userMessageIndex === -1) {
    uni.showToast({
      title: '找不到对应的用户问题',
      icon: 'none'
    })
    return
  }
  
  const userQuestion = messages.value[userMessageIndex].text
  const aiMessage = messages.value[lastAiMessageIndex]
  
  console.log('重新生成回答，用户问题:', userQuestion)
  
  // 设置处理状态
  isTyping.value = true
  isSubmitting.value = true
  
  try {
    // 移除原来的AI回答
    messages.value.splice(lastAiMessageIndex, 1)
    
    // 添加思考指示器
    const thinkingMsg = { 
      id: 'thinking-' + Date.now(), 
      role: 'assistant', 
      text: '...', 
      thinking: true 
    }
    messages.value.push(thinkingMsg)
    
    // 滚动到底部
    await nextTick()
    scrollTop.value = 9999999
    scrollToBottom()
    
    // 构建请求参数，与sendQuestion保持一致
    const payload = {
      question: userQuestion,
      saveRecord: true  // 确保保存记录
    }
    
    // 添加会话ID
    if (currentSessionId.value) {
      payload.sessionId = currentSessionId.value
    }

    // 统一设置模型与模式
    applyModelAndModeToPayload(payload)
    
    // 添加参数控制
    payload.temperature = temperature.value
    payload.maxTokens = maxTokens.value

    console.log('重新生成回答请求:', payload)
    
    // 仅调用 generate-answer；发现无效 sessionId 时自动清空并无 session 重试
    let data
    const callGenerate = async (useSession) => {
      const req = { ...payload }
      if (!useSession) {
        delete req.sessionId
      }
      const res = await generateAnswer(req)
      const d = res?.data || res
      // 后端可能用HTTP 400返回，但这里仍走成功回调；显式校验业务码
      if (typeof d?.code === 'number' && d.code !== 200) {
        const err = new Error(d?.message || '生成答案失败')
        err.data = d
        throw err
      }
      return d
    }

    try {
      // 如果本地有 sessionId，先校验是否存在；不存在则先清理
      if (currentSessionId.value) {
        try {
          await getSessionDetail(currentSessionId.value)
        } catch (_) {
          console.warn('本地 sessionId 在服务器不存在，先清理再创建新会话')
          currentSessionId.value = ''
          uni.removeStorageSync('qa_session_id')
        }
      }
      // 调用 generate-answer（带当前 sessionId，如果仍存在）
      data = await callGenerate(Boolean(currentSessionId.value))
    } catch (err1) {
      const msg = err1?.data?.message || err1?.message || ''
      const isSessionFkError = /session_id|foreign key|不在|不存在|FK_conversations/i.test(msg)
      if (isSessionFkError && currentSessionId.value) {
        // 清除无效 sessionId 并重试创建新会话
        console.warn('检测到无效 sessionId，清理后重试创建新会话:', currentSessionId.value)
        currentSessionId.value = ''
        uni.removeStorageSync('qa_session_id')
        try {
          data = await callGenerate(false)
        } catch (err2) {
          throw err2
        }
      } else {
        // 非外键错误，直接抛出，交由上层错误处理
        throw err1
      }
    }
    
    console.log('收到重新生成回复:', data)
    
    // 处理返回的会话ID
    if (data?.sessionId) {
      if (!currentSessionId.value) {
        currentSessionId.value = data.sessionId
        uni.setStorageSync('qa_session_id', data.sessionId)
        console.log('保存新的会话ID:', data.sessionId)
      }
      
      // 更新当前对话的sessionId
      if (chatStore.value && chatStore.value.getCurrentChat) {
        chatStore.value.getCurrentChat.sessionId = data.sessionId
        chatStore.value.saveToStorage()
      }
    }

    const answerText = data?.answer || data?.content || '[无内容]'
    
    // 移除思考指示器消息
    messages.value = messages.value.filter(msg => !msg.thinking)
    
    // 记录助手回复到聊天历史
    if (chatStore.value) {
      chatStore.value.addMessage('assistant', answerText, currentSessionId.value)
    }
    
    await typeWriter(String(answerText))
    
    // AI回复完成后立即滚动，确保消息完全可见
    scrollToBottom()
    
    // 根据平台使用不同的滚动策略
    if (!showNavbar.value) {
      // 小程序端：只进行一次滚动，避免跳动
      setTimeout(() => {
        scrollToBottom()
      }, 200)
    } else {
      // H5/APP端：保持原有滚动频率
      setTimeout(() => {
        scrollToBottom()
      }, 50)
      
      setTimeout(() => {
        scrollToBottom()
      }, 100)
      
      setTimeout(() => {
        scrollToBottom()
      }, 200)
      
      setTimeout(() => {
        scrollToBottom()
      }, 500)
      
      setTimeout(() => {
        scrollToBottom()
      }, 1000)
    }
    
    // 问答完成后，可选择性地同步到服务器
    if (chatStore.value && chatStore.value.shouldSync()) {
      setTimeout(() => {
        chatStore.value.syncFromServer()
      }, 2000) // 延迟2秒同步，避免影响用户体验
    }
    
    // 更新侧边栏显示
    nextTick(() => {
      // 强制更新计算属性
      if (chatStore.value) {
        chatStore.value.saveToStorage()
      }
    })
    
    uni.showToast({
      title: '重新生成完成',
      icon: 'success'
    })
  } catch (err) {
    console.error('重新生成回答失败:', err)
    
    // 移除思考指示器消息
    messages.value = messages.value.filter(msg => !msg.thinking)
    
    // 重置输入框状态
    isTyping.value = false
    isSubmitting.value = false
    
    // 使用AI错误处理函数
    const errorInfo = handleAIError(err)
    
    uni.showToast({ 
      title: errorInfo.message, 
      icon: 'error',
      duration: 3000
    })
    
    // 添加错误消息到聊天记录
    const errorMsg = { 
      id: 'm' + Date.now() + '-e', 
      role: 'assistant', 
      text: errorInfo.message, 
      typing: false 
    }
    messages.value.push(errorMsg)
    
    // 记录错误消息到聊天历史
    if (chatStore.value) {
      chatStore.value.addMessage('assistant', errorInfo.message, currentSessionId.value)
    }
  } finally {
    // 重置状态
    isTyping.value = false
    isSubmitting.value = false
    
    // 最终滚动到底部
    await nextTick()
    const getScrollValue = () => {
      return !showNavbar.value ? 100000 : 9999999
    }
    scrollTop.value = getScrollValue()
    scrollToBottom()
  }
}
const shareMessage = () => {
  uni.showToast({
    title: '分享功能开发中',
    icon: 'none'
  })
}
const deepThinking = () => {
  uni.showToast({
    title: '深度思考模式',
    icon: 'none' 
  })
}
const networkSearch = () => {
  uni.showToast({
    title: '联网搜索模式',
    icon: 'none'
  })
}
const startVoice = () => {
  uni.showToast({
    title: '语音功能开发中',
    icon: 'none'
  })
}
const showMore = () => {
  uni.showToast({
    title: '更多功能开发中',
    icon: 'none'
  })
}

const handleBottomInput = (e) => {
  bottomMessageText.value = e.detail.value
}
const sendMessage = () => {
  if (!messageText.value.trim()) {
    uni.showToast({
      title: '请输入消息',
      icon: 'none'
    })
    return
  }
  // 这里可以调用API发送消息
  console.log('发送消息:', messageText.value)
  // 清空输入框
  messageText.value = ''
  uni.showToast({
    title: '消息已发送',
    icon: 'success'
  })
}

const sendQuestion = async () => {
  // 防止重复提交
  if (isTyping.value || isSubmitting.value) {
    console.log('正在处理中，忽略重复提交')
    return
  }
  
  // 只有在手动发送时才重置参数处理标志
  // 自动发送时保持标志状态，避免重复处理
  // 这里不需要重置，保持原有逻辑
  
  const content = questionText.value.trim()
  console.log('准备发送问题:', content)
  
  if (!content) {
    uni.showToast({
      title: '请输入问题',
      icon: 'none'
    })
    return
  }
  
  // 立即设置处理状态，防止重复提交
  isTyping.value = true
  isSubmitting.value = true
  
  // 确保有当前对话（如果没有则在添加消息时自动创建）
  
  // 记录用户消息到聊天历史
  if (chatStore.value) {
    chatStore.value.addMessage('user', content, currentSessionId.value)
  }
  
  const userMsg = { id: 'm' + Date.now() + '-u', role: 'user', text: content, typing: false }
  messages.value.push(userMsg)
  // 发送后清空输入框，无论是手动发送还是自动发送
  questionText.value = ''
  
  // 立即滚动到底部，确保用户消息可见
  await nextTick()
  
  // 根据平台设置滚动位置
  const getScrollValue = () => {
    return !showNavbar.value ? 999999 : 9999999
  }
  
  // 强制设置滚动位置
  scrollTop.value = getScrollValue()
  scrollToBottom()
  
  // 根据平台使用不同的滚动策略
  if (!showNavbar.value) {
    // 小程序端：使用多次滚动确保效果
    setTimeout(() => {
      scrollToBottom()
    }, 50)
    
    setTimeout(() => {
      scrollToBottom()
    }, 150)
    
    setTimeout(() => {
      scrollToBottom()
    }, 300)
  } else {
    // H5/APP端：保持原有滚动频率
    setTimeout(() => {
      scrollTop.value = getScrollValue()
      scrollToBottom()
    }, 10)
    
    setTimeout(() => {
      scrollTop.value = getScrollValue()
      scrollToBottom()
    }, 25)
    
    setTimeout(() => {
      scrollTop.value = getScrollValue()
      scrollToBottom()
    }, 50)
    
    setTimeout(() => {
      scrollTop.value = getScrollValue()
      scrollToBottom()
    }, 100)
    
    setTimeout(() => {
      scrollTop.value = getScrollValue()
      scrollToBottom()
    }, 200)
  }

  // 接入真实接口
  try {
    // 添加AI思考指示器消息（省略号）
    const thinkingMsg = { id: 'thinking-' + Date.now(), role: 'assistant', text: '...', thinking: true }
    messages.value.push(thinkingMsg)
    await nextTick()
    scrollToBottom()
    
    const payload = {
      question: content,
      saveRecord: true  // 确保保存记录
    }
    
    // 添加会话ID
    if (currentSessionId.value) {
      payload.sessionId = currentSessionId.value
    }

    // 统一设置模型与模式
    applyModelAndModeToPayload(payload)
    
    // 添加参数控制
    payload.temperature = temperature.value
    payload.maxTokens = maxTokens.value

    console.log('发送问答请求:', payload)
    
    // 优先使用AI接口，fallback到qa接口
    let res, data
    try {
      res = await askAI(payload)
      data = res?.data || res
    } catch (aiError) {
      console.warn('AI接口调用失败，尝试qa接口:', aiError)
      res = await generateAnswer(payload)
      data = res?.data || res
    }
    
    console.log('收到问答回复:', data)

    // 如果后端以200返回但内容为厂商鉴权错误（如星火 AppIdNoAuthError），在前端做兜底处理并自动切回 DeepSeek
    const answerCandidate = String(data?.answer || data?.content || data?.message || '')
    const vendorAuthPattern = /AppIdNoAuthError|AppId\s*no\s*auth|xunfei|讯飞|星火/i
    if (vendorAuthPattern.test(answerCandidate) && /no\s*auth|AppIdNoAuthError|key|secret|appid/i.test(answerCandidate)) {
      console.warn('检测到厂商鉴权类错误内容，准备切换为 DeepSeek 并重试一次')
      // 切换到 DeepSeek
      const deepseekIdx = modelOptions.value.findIndex(m => m.type === 'deepseek')
      selectedModelIndex.value = deepseekIdx !== -1 ? deepseekIdx : 0
      // 组装新的载荷并重试一次
      const retryPayload = { ...payload }
      applyModelAndModeToPayload(retryPayload)
      try {
        const retryRes = await askAI(retryPayload)
        data = retryRes?.data || retryRes
        uni.showToast({ title: '当前模型无权限，已切换为 DeepSeek 并重试', icon: 'none' })
      } catch (retryErr) {
        console.error('DeepSeek 重试失败:', retryErr)
      }
    }

    // 处理返回的会话ID
    if (data?.sessionId) {
      if (!currentSessionId.value) {
      currentSessionId.value = data.sessionId
      uni.setStorageSync('qa_session_id', data.sessionId)
        console.log('保存新的会话ID:', data.sessionId)
      }
      
      // 更新当前对话的sessionId
      if (chatStore.value && chatStore.value.getCurrentChat) {
        chatStore.value.getCurrentChat.sessionId = data.sessionId
        chatStore.value.saveToStorage()
      }
    }

    const answerText = data?.answer || data?.content || '[无内容]'
    
    // 移除思考指示器消息
    messages.value = messages.value.filter(msg => !msg.thinking)
    
    // 记录助手回复到聊天历史
    if (chatStore.value) {
      chatStore.value.addMessage('assistant', answerText, currentSessionId.value)
    }
    
    await typeWriter(String(answerText))
    
    // AI回复完成后立即滚动，确保消息完全可见
    scrollToBottom()
    
    // 根据平台使用不同的滚动策略
    if (!showNavbar.value) {
      // 小程序端：只进行一次滚动，避免跳动
      setTimeout(() => {
        scrollToBottom()
      }, 200)
    } else {
      // H5/APP端：保持原有滚动频率
      setTimeout(() => {
        scrollToBottom()
      }, 50)
      
      setTimeout(() => {
        scrollToBottom()
      }, 100)
      
      setTimeout(() => {
        scrollToBottom()
      }, 200)
      
      setTimeout(() => {
        scrollToBottom()
      }, 500)
      
      setTimeout(() => {
        scrollToBottom()
      }, 1000)
    }
    
    // 问答完成后，可选择性地同步到服务器
    if (chatStore.value && chatStore.value.shouldSync()) {
      setTimeout(() => {
        chatStore.value.syncFromServer()
      }, 2000) // 延迟2秒同步，避免影响用户体验
    }
    
    // 更新侧边栏显示
    nextTick(() => {
      // 强制更新计算属性
      if (chatStore.value) {
        chatStore.value.saveToStorage()
      }
    })
    
  } catch (err) {
    console.error('生成回答失败:', err)
    
    // 移除思考指示器消息
    messages.value = messages.value.filter(msg => !msg.thinking)
    
    // 重置输入框状态
    isTyping.value = false
    isSubmitting.value = false
    
    // 使用AI错误处理函数
    const errorInfo = handleAIError(err)
    
    uni.showToast({ 
      title: errorInfo.message, 
      icon: 'none',
      duration: 3000
    })
    
    // 若为模型厂商鉴权问题（如星火AppIdNoAuthError），自动切回可用模型
    try {
      if (errorInfo.type === 'vendor_auth') {
        const deepseekIdx = modelOptions.value.findIndex(m => m.type === 'deepseek')
        selectedModelIndex.value = deepseekIdx !== -1 ? deepseekIdx : 0
        uni.showToast({
          title: '当前模型未配置鉴权，已切换为 DeepSeek',
          icon: 'none',
          duration: 2500
        })
      }
    } catch (e) {
      // 忽略兜底错误
    }
    
    // 记录错误消息到聊天历史
    if (chatStore.value) {
      chatStore.value.addMessage('assistant', `抱歉，回答生成失败：${errorInfo.message}`, currentSessionId.value)
      
      // 更新侧边栏显示
      nextTick(() => {
        chatStore.value.saveToStorage()
      })
    }
  }
}

const handleInput = (e) => {
  questionText.value = e.detail.value
}

const handleKeyDown = (e) => {
  // 检查是否按下回车键（且没有按Shift键）
  if (e.keyCode === 13 && !e.shiftKey) {
    e.preventDefault() // 阻止默认的换行行为
    if (questionText.value.trim() && !isTyping.value && !isSubmitting.value) {
      sendQuestion()
    }
  }
}

const toggleAdvancedSettings = () => {
  showAdvancedSettings.value = !showAdvancedSettings.value
}

const toggleDeepMode = () => {
  isDeepMode.value = !isDeepMode.value
  // 同步下拉选择的索引
  const target = isDeepMode.value ? 'reasoner' : 'chat'
  const idx = xunfeiModeOptions.value.findIndex(m => m.value === target)
  if (idx !== -1) {
    xunfeiModeIndex.value = idx
  }
  console.log('深度思考模式:', isDeepMode.value ? '开启(推理)' : '关闭(普通)')
}

// 统一设置模型与模式到请求载荷
const applyModelAndModeToPayload = (payload) => {
  const mode = xunfeiModeOptions.value[xunfeiModeIndex.value]?.value || 'chat'
  if (selectedModelItem.value?.type === 'xunfei') {
    // 星火V2
    payload.model = 'x1'
    payload.xunfeiVersion = 'v2'
    payload.xunfeiMode = mode
  } else if (selectedModelItem.value?.type === 'deepseek') {
    // DeepSeek：根据模式切换不同的模型值
    payload.model = mode === 'reasoner' ? 'deepseek-reasoner' : 'deepseek-chat'
    payload.deepseekMode = mode
  }
}

const attachFile = () => {
  uni.showToast({
    title: '附件功能开发中',
    icon: 'none'
  })
}

const sendBottomMessage = () => {
  if (!bottomMessageText.value.trim()) {
    uni.showToast({
      title: '请输入内容',
      icon: 'none'
    })
    return
  }
  // 这里可以调用API发送底部消息
  console.log('发送底部消息:', bottomMessageText.value)
  // 清空输入框
  bottomMessageText.value = ''
  uni.showToast({
    title: '内容已发送',
    icon: 'success'
  })
}

const uploadFile = () => {
  uni.showToast({
    title: '上传功能开发中',
    icon: 'none'
  })
}
</script>

<style scoped>
body {
  background: #f5f6fa;
}

.chat-container {
  min-height: 100vh;
  height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow-x: hidden;
  padding-bottom: 20px;
}

/* PC端特殊处理 - 确保页面占满整个屏幕 */
@media (min-width: 769px) {
  .chat-container {
    height: 100vh !important;
    min-height: 100vh !important;
    display: flex;
    flex-direction: column;
  }
  
  /* 确保聊天内容区域能够填充剩余空间 */
  .chat-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: calc(100vh - 120px); /* 减去头部高度 */
  }
}

/* 侧边栏样式 */
.sidebar {
  position: fixed;
  top: 0;
  left: -300px;
  width: 300px;
  height: 100vh;
  background: #ffffff;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1), 0 0 20px rgba(102, 126, 234, 0.1);
  z-index: 1000;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  flex-direction: column;
  transform: translateX(-100%);
  /* 性能优化 */
  will-change: transform;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
}

/* 响应式侧边栏 */
@media (max-width: 480px) {
  .sidebar {
    width: 280px;
  }
  
  .chat-title {
    max-width: 160px;
  }
  
  .chat-history-list {
    max-height: 250px;
  }
  
  .history-title {
    font-size: 13px;
  }
  
  .chat-history-item {
    padding: 10px 14px;
  }
}

@media (max-width: 360px) {
  .sidebar {
    width: 260px;
  }
  
  .chat-title {
    max-width: 140px;
  }
  
  .sidebar-content {
    padding: 16px;
  }
}

/* 侧边栏打开状态 */
.sidebar-open {
  left: 0;
  transform: translateX(0);
  box-shadow: 2px 0 20px rgba(0, 0, 0, 0.15), 0 0 30px rgba(102, 126, 234, 0.2);
}

/* 侧边栏头部样式 */
.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.sidebar-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, #667eea 50%, transparent 100%);
}

/* 侧边栏Logo容器 */
.sidebar-logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 侧边栏Logo图标 */
.sidebar-logo-icon {
  font-size: 24px;
  color: #333;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

/* 侧边栏Logo文字 */
.sidebar-logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 侧边栏关闭按钮 */
.sidebar-close {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  font-size: 16px;
  color: #6c757d;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s ease;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  position: relative;
  overflow: hidden;
}

.sidebar-close::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: #667eea;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
}

.sidebar-close:hover::before {
  width: 100%;
  height: 100%;
}

/* 侧边栏关闭按钮悬停效果 */
.sidebar-close:hover {
  background: #e9ecef;
  color: #495057;
  transform: scale(1.05);
}

.sidebar-close:hover .sidebar-close {
  color: #fff;
  z-index: 1;
}

/* 侧边栏内容区域 */
.sidebar-content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow-y: auto;
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
  /* 性能优化 */
  will-change: scroll-position;
  -webkit-overflow-scrolling: touch;
}

.sidebar-content::-webkit-scrollbar {
  width: 6px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.sidebar-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 新建对话按钮 */
.new-chat-btn {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.new-chat-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s ease;
  z-index: -1;
}

/* 新建对话按钮悬停效果 */
.new-chat-btn:hover {
  background: #f0f0f0;
  border-color: #d0d0d0;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
  color: #fff;
}

.new-chat-btn:hover::before {
  left: 0;
}

.new-chat-btn:hover .new-chat-icon,
.new-chat-btn:hover .new-chat-text,
.new-chat-btn:hover .new-chat-shortcut {
  color: #fff;
  z-index: 1;
}

/* 新建对话按钮图标 */
.new-chat-icon {
  font-size: 16px;
  font-weight: bold;
  color: #667eea;
}

/* 新建对话按钮文字 */
.new-chat-text {
  flex: 1;
  font-weight: 500;
}

/* 新建对话按钮快捷键提示 */
.new-chat-shortcut {
  font-size: 12px;
  color: #666;
  background: #e8e8e8;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 侧边栏菜单容器 */
.sidebar-menu {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 侧边栏菜单项 */
.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #333;
  background: #ffffff;
  border: 1px solid #f0f0f0;
  position: relative;
  overflow: hidden;
}

.menu-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s ease;
  z-index: -1;
}

/* 侧边栏菜单项悬停效果 */
.menu-item:hover {
  background: #f8f9fa;
  border-color: #e0e0e0;
  color: #fff;
  transform: translateX(4px);
}

.menu-item:hover::before {
  left: 0;
}

.menu-item:hover .menu-icon,
.menu-item:hover .menu-text {
  color: #fff;
  z-index: 1;
}

/* 侧边栏菜单项图标 */
.menu-icon {
  font-size: 18px;
  color: #667eea;
}

/* 侧边栏菜单项文字 */
.menu-text {
  font-size: 14px;
  font-weight: 500;
}

/* 历史对话列表 */
.history-list {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 历史对话项 */
.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  transition: all 0.2s ease;
  color: #333;
  background: #ffffff;
  border: 1px solid #f0f0f0;
  margin-bottom: 4px;
  min-height: 60px;
  overflow: hidden;
}

/* 历史对话项内容区域 */
.history-item-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  cursor: pointer;
}

/* 历史对话项操作区域 */
.history-item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  min-width: 40px;
  justify-content: flex-end;
}

/* 删除按钮 */
.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 0;
  min-width: 32px;
  min-height: 32px;
}

.delete-btn:hover {
  background: #ff4757;
  transform: scale(1.1);
}

.delete-btn:active {
  transform: scale(0.95);
}

.delete-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

/* 编辑按钮 */
.edit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 0;
  min-width: 32px;
  min-height: 32px;
  margin-right: 8px;
}

.edit-btn:hover {
  background: #667eea;
  transform: scale(1.1);
}

.edit-btn:active {
  transform: scale(0.95);
}

.edit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

/* 编辑图标 */
.edit-icon {
  font-size: 16px;
  color: #999;
  transition: color 0.2s ease;
  line-height: 1;
}

.edit-btn:hover .edit-icon {
  color: #ffffff;
}

/* 删除图标 */
.delete-icon {
  font-size: 16px;
  color: #999;
  transition: color 0.2s ease;
  line-height: 1;
}

.delete-btn:hover .delete-icon {
  color: #ffffff;
}

/* 小程序端删除按钮样式 */
.delete-btn {
  background: transparent;
  border: none;
}

.delete-btn:active {
  background: #ff4757;
  transform: scale(0.95);
}

.delete-btn:active .delete-icon {
  color: #ffffff;
}



/* 刷新按钮 */
.refresh-btn {
  margin-top: 4px;
}

.refresh-btn .menu-icon {
  color: #667eea;
}

.refresh-btn:hover {
  background: #f0f4ff;
}

.refresh-btn:hover .menu-text {
  color: #667eea;
}

.refresh-btn.refreshing .menu-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 清空所有对话按钮 */
/* 清空按钮已移除 */

/* 历史对话项悬停效果 */
.history-item:hover {
  background: #f8f9fa;
  border-color: #e0e0e0;
  transform: translateX(2px);
}

/* 历史对话图标 */
.history-icon {
  font-size: 16px;
  color: #667eea;
  flex-shrink: 0;
}

/* 历史对话内容区域 */
.history-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0; /* 防止文本溢出 */
  max-width: calc(100% - 60px); /* 为操作按钮留出空间 */
  overflow: hidden;
}

/* 历史对话标题 */
.history-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  word-break: break-all;
  display: block;
}

/* 历史对话详情区域 */
.history-details {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  line-height: 1.2;
}

/* 历史对话消息数量 */
.history-message-count {
  color: #667eea;
  font-weight: 500;
}

/* 历史对话时间 */
.history-time {
  color: #999;
}

/* 历史对话加载状态 */
.history-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  color: #999;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #f0f0f0;
  border-top: 2px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
  color: #999;
}

/* 历史对话空状态 */
.history-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #999;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

/* 侧边栏底部区域 */
.sidebar-footer {
  padding: 20px; /* 内边距 */
  border-top: 1px solid #f0f0f0; /* 顶部边框 */
  background: #ffffff; /* 白色背景 */
}

/* 底部个人信息菜单项 */
.sidebar-footer .menu-item {
  margin: 0; /* 移除外边距 */
  border: 1px solid #f0f0f0; /* 边框 */
  background: #ffffff; /* 白色背景 */
}

/* 底部个人信息菜单项悬停效果 */
.sidebar-footer .menu-item:hover {
  background: #f8f9fa; /* 悬停时背景色 */
  border-color: #e0e0e0; /* 悬停时边框色 */
}

/* 历史对话区域样式 */
.chat-history-section {
  margin-top: 20px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
  position: relative;
}

.chat-history-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent 0%, #667eea 50%, transparent 100%);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.history-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-left: 12px;
}

.history-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  width: 4px;
  height: 16px;
  background: #667eea;
  border-radius: 2px;
  transform: translateY(-50%);
}

.history-count {
  font-size: 12px;
  color: #666;
  background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
}

.chat-history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
  /* 性能优化 */
  will-change: scroll-position;
  -webkit-overflow-scrolling: touch;
}

.chat-history-list::-webkit-scrollbar {
  width: 6px;
}

.chat-history-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-history-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-history-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.chat-history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.chat-history-item:hover {
  background: #e9ecef;
  border-color: #dee2e6;
  transform: translateX(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chat-history-item.active {
  background: #667eea;
  border-color: #667eea;
  color: #fff;
}

.chat-history-item.active .chat-title,
.chat-history-item.active .chat-time {
  color: #fff;
}

.chat-item-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.chat-title {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
}

.chat-time {
  font-size: 11px;
  color: #666;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  background: rgba(0, 0, 0, 0.05);
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.chat-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.chat-history-item:hover .chat-actions {
  opacity: 1;
}

.delete-icon {
  font-size: 14px;
  color: #dc3545;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
}

.delete-icon::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: #dc3545;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
  z-index: -1;
}

.delete-icon:hover {
  background: #f8d7da;
  transform: scale(1.1);
  color: #fff;
}

.delete-icon:hover::before {
  width: 100%;
  height: 100%;
}

.chat-history-item.active .delete-icon {
  color: #fff;
}

.chat-history-item.active .delete-icon:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 空状态样式 */
.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.empty-text {
  font-size: 14px;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 12px;
  color: #ccc;
}

/* 加载状态样式 */
.loading-history {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

/* 遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(2px);
}

/* 遮罩层显示状态 */
.overlay-show {
  opacity: 1;
  visibility: visible;
}

.header {
  width: 100%;
  max-width: 600px;
  height: calc(60px + env(safe-area-inset-top, 0px));
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: calc(10px + env(safe-area-inset-top, 0px)) 16px 0 16px;
  border-bottom: 1px solid #e9ecef;
  border-radius: 20px 20px 0 0;
  box-sizing: border-box;
  margin: 0 auto;
}
.header-left, .header-right {
  width: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.header-center {
  flex: 1;
  text-align: center;
}
.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}
.back-icon, .share-icon, .menu-icon {
  font-size: 20px;
  color: #495057;
  cursor: pointer;
  font-weight: 400;
}

/* 小程序模式顶部样式 */
.mp-header {
  width: 100%;
  background-color: #fff;
  color: #000;
}

.mp-status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: calc(16px + env(safe-area-inset-top, 0px)) 16px 4px 16px;
  font-size: 14px;
  background: #fff;
  height: calc(28px + env(safe-area-inset-top, 0px));
}

.mp-time {
  font-weight: 600;
}

.mp-status-icons {
  display: flex;
  gap: 4px;
}

.mp-icon {
  font-size: 12px;
}

.mp-nav {
  margin-top: 28px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px 12px 16px;
  background: #faf8f8;
  border-bottom: 1px solid #333;
}

.mp-back, .mp-more, .mp-menu {
  font-size: 18px;
  color: #101010;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background 0.2s;
}

.mp-back:hover, .mp-more:hover, .mp-menu:hover {
  background: rgba(255, 255, 255, 0.1);
}

.mp-title {
  font-size: 16px;
  font-weight: 600;
  color: #101010;
}

.chat-messages {
  flex: 1;
  width: 100%;
  max-width: 600px;
  height: calc(100vh - 280px);
  min-height: 300px;
  padding: 16px 16px 16px 4px;
  background: #f8f9fa;
  overflow-y: auto;
  box-sizing: border-box;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  scroll-behavior: smooth;
}

/* 小程序模式聊天区域样式 */
.chat-messages-mp {
  max-width: 100%;
  height: calc(100vh - 280px);
  min-height: 300px;
  padding: 8px 12px 8px 4px;
  background: #f0f0f0;
  display: flex;
  flex-direction: column;
  scroll-behavior: smooth;
  overflow-y: auto;
  box-sizing: border-box;
}

/* 滚动到底部按钮 */
.scroll-to-bottom-btn {
  position: fixed;
  bottom: 140px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(108, 92, 231, 0.3);
  z-index: 1000;
  cursor: pointer;
  transition: all 0.3s ease;
}

.scroll-to-bottom-btn:hover {
  transform: scale(1.1);
}

.scroll-icon {
  color: #fff;
  font-size: 16px;
  font-weight: bold;
}
.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  width: 100%;
  box-sizing: border-box;
}
.message-item.message-left {
  justify-content: flex-start;
}
.message-item.message-left .message-avatar {
  margin-right: 8px;
}
.message-item.message-left .message-content {
  margin-left: 0;
}
.message-item.message-left .message-bubble {
  margin-left: 0;
}
.message-item.message-right {
  justify-content: flex-end;
  text-align: right;
}
.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 4px;
  flex-shrink: 0;
  box-shadow: 0 2px 6px rgba(108, 92, 231, 0.2);
}
.avatar-icon {
  font-size: 14px;
  color: #fff;
}
.message-content {
  max-width: 75%;
  min-width: 0;
  flex: 1;
  margin-left: auto;
}
.message-bubble {
  background: #fff;
  padding: 10px 14px;
  border-radius: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 6px;
  word-wrap: break-word;
  overflow-wrap: break-word;
  max-width: 100%;
  box-sizing: border-box;
  border: 1px solid #e9ecef;
}
.user-bubble {
  background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(108, 92, 231, 0.3);
  display: inline-block;
  min-width: 50px;
  max-width: 70vw;
  margin-left: auto;
  margin-right: 0;
}
.message-text {
  font-size: 14px;
  line-height: 1.4;
  color: #495057;
  word-break: break-word;
  overflow-wrap: break-word;
  display: block;
  width: 100%;
}
.user-bubble .message-text {
  color: #fff;
}
.message-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
  margin-top: 6px;
  opacity: 0.6;
}
.action-icon {
  font-size: 12px;
  color: #adb5bd;
  cursor: pointer;
  padding: 3px;
  border-radius: 3px;
  transition: all 0.2s ease;
}
.action-icon:hover {
  background: #f1f3f4;
  color: #6c757d;
}

.bottom-actions {
  display: flex;
  gap: 12px;
  padding: 10px 0 8px 0;
  background: transparent;
  border: none;
  box-shadow: none;
  width: 100%;
  justify-content: center;
  max-width: 600px;
  margin: 0 auto 2px auto;
}
.action-btn {
  flex: none;
  min-width: 120px;
  height: 40px;
  border: none;
  border-radius: 14px;
  background: #f4f5f7;
  color: #333;
  font-size: 16px;
  font-weight: 500;
  box-shadow: none;
  margin: 0 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: background 0.2s;
}
.action-btn:active {
  background: #ececec;
}
.deep-thinking {
  background: #ece9fc;
  color: #6c5ce7;
}
.network-search {
  background: #f4f5f7;
  color: #495057;
}

/* H5/APP模式底部输入区域样式 */
.input-bottom-h5 {
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  margin: 8px auto 16px auto;
  padding: 18px 20px 16px 20px;
  width: 100%;
  max-width: 600px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  position: relative;
  z-index: 10;
}

.question-input-h5 {
  width: 100%;
  min-height: 40px;
  max-height: 80px;
  font-size: 16px;
  border: 1px solid #e5e7eb;
  border-radius: 16px;
  padding: 10px 14px;
  background: #f8f9fa;
  color: #222;
  outline: none;
  box-sizing: border-box;
  margin-bottom: 12px;
  resize: none;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  transition: all 0.3s ease;
}

.question-input-h5:disabled {
  background: #f1f3f4;
  color: #9ca3af;
  cursor: not-allowed;
  opacity: 0.7;
}

.input-actions-h5 {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: 8px;
  flex-wrap: nowrap;
  min-height: 44px;
}

/* 小程序模式底部输入区域样式 */
.input-bottom-mp {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  margin: 6px 12px 20px 12px;
  padding: 14px 16px 16px 16px;
  width: calc(100% - 24px);
  max-width: none;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  position: relative;
  z-index: 10;
}
.question-input-bottom {
  width: 100%;
  min-height: 36px;
  max-height: 72px;
  font-size: 14px;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  color: #222;
  outline: none;
  box-sizing: border-box;
  margin-bottom: 10px;
  resize: none;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  transition: all 0.3s ease;
}

.question-input-bottom:disabled {
  background: #f1f3f4;
  color: #9ca3af;
  cursor: not-allowed;
  opacity: 0.7;
}
.input-actions-bottom {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: 6px;
  flex-wrap: nowrap;
  min-height: 40px;
}

/* 统一底部按钮样式 */
.deep-btn {
  font-size: 26rpx;
  padding: 8rpx 12rpx;
  border: none;
  border-radius: 12rpx;
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6rpx;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(102, 126, 234, 0.1);
  flex-shrink: 0;
  white-space: nowrap;
}

.deep-btn:hover {
  background: rgba(102, 126, 234, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.2);
}

.deep-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(102, 126, 234, 0.1);
}

.deep-icon {
  font-size: 20rpx;
  color: #667eea;
}

.deep-text {
  font-size: 24rpx;
  color: #667eea;
}

/* 统一按钮基础样式 */
.settings-btn, .attach-btn, .send-btn {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  background: #f4f5f7;
  border: 1.5px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin: 0;
  font-size: 16px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.settings-btn:hover, .attach-btn:hover {
  background: #e9ecef;
  border-color: #dee2e6;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.settings-btn:active, .attach-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 发送按钮特殊样式 */
.send-btn {
  background: #6c5ce7;
  border: none;
  color: #fff;
  border-radius: 50%;
  font-size: 16px;
}
.send-icon {
  font-size: 16px;
  line-height: 1;
}

.send-btn:hover {
  background: #5a4fcf;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(108, 92, 231, 0.4);
}

.send-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(108, 92, 231, 0.3);
}

/* 模型选择器统一样式 */
.model-selector {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 26rpx;
  color: #666;
  padding: 8rpx 16rpx;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 12rpx;
  margin-right: 12rpx;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid transparent;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.model-selector:hover {
  background: rgba(0, 0, 0, 0.08);
  border-color: #e5e7eb;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.model-selector:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.model-text {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

.model-arrow {
  font-size: 20rpx;
  color: #999;
  transition: transform 0.3s ease;
}

.model-selector:hover .model-arrow {
  transform: translateY(2px);
}

/* 禁用状态样式 */
.model-selector.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: rgba(0, 0, 0, 0.03);
  pointer-events: none;
}

.model-selector.disabled .model-text {
  color: #999;
}

.model-selector.disabled .model-arrow {
  color: #ccc;
}

/* 深度思考切换按钮样式 */
.deep-thinking-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8rpx 16rpx;
  border: 2rpx solid #e5e7eb;
  border-radius: 20rpx;
  background: #f9fafb;
  color: #6b7280;
  font-size: 24rpx;
  font-weight: 500;
  transition: all 0.2s ease;
  cursor: pointer;
  min-width: 120rpx;
  height: 36px;
  box-sizing: border-box;
  flex-shrink: 0;
  margin: 0 8rpx;
  position: relative;
  z-index: 10;
}

.deep-thinking-toggle.active {
  background: #667eea;
  color: #fff;
  border-color: #667eea;
  box-shadow: 0 1rpx 4rpx rgba(102, 126, 234, 0.2);
}

.deep-thinking-toggle:active {
  transform: scale(0.98);
  background: #f3f4f6;
}

.deep-thinking-toggle.active:active {
  background: #5a67d8;
}

/* 禁用状态样式 */
.deep-thinking-toggle:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f3f4f6;
  color: #9ca3af;
  border-color: #d1d5db;
  pointer-events: none;
}

.deep-thinking-toggle:disabled.active {
  background: #9ca3af;
  color: #6b7280;
  border-color: #9ca3af;
}

.toggle-text {
  font-size: 24rpx;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  color: inherit;
  font-weight: inherit;
  white-space: nowrap;
}

/* 分隔符样式 */
.separator {
  width: 0;
  height: 24px;
  border-left: 1px solid #e5e7eb;
  margin: 0 6px;
}

/* 左右操作区域统一样式 */
.action-left,
.action-right {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  min-width: 0;
}

.action-left {
  flex-shrink: 0;
}

.action-right {
  flex: 1;
  justify-content: flex-end;
  gap: 6px;
}

/* 小程序模式按钮样式调整 */
.input-actions-bottom .deep-btn {
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 10rpx;
}

.input-actions-bottom .settings-btn,
.input-actions-bottom .attach-btn,
.input-actions-bottom .send-btn {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  font-size: 14px;
}

.input-actions-bottom .model-selector {
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 10rpx;
  margin-right: 16rpx;
}

.input-actions-bottom .separator {
  height: 20px;
  margin: 0 4px;
}

.input-actions-bottom .deep-thinking-toggle {
  padding: 6rpx 12rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
  min-width: 100rpx;
  height: 32px;
  display: flex;
  background: #f9fafb;
  color: #6b7280;
  flex-shrink: 0;
  margin: 0 6rpx;
  position: relative;
  z-index: 10;
  border: 2rpx solid #e5e7eb;
  font-weight: 500;
}

.input-actions-bottom .toggle-text {
  font-size: 22rpx;
}

/* 响应式按钮样式调整 */
@media (max-width: 480px) {
  .deep-btn {
    font-size: 24rpx;
    padding: 6rpx 12rpx;
  }
  
  .deep-icon {
    font-size: 18rpx;
  }
  
  .deep-text {
    font-size: 22rpx;
  }
  
  .model-selector {
    font-size: 24rpx;
    padding: 6rpx 12rpx;
    margin-right: 8rpx;
  }
  
  .model-text {
    font-size: 22rpx;
  }
  
  .model-arrow {
    font-size: 18rpx;
  }
  
  .deep-thinking-toggle {
    padding: 6rpx 12rpx;
    border-radius: 16rpx;
    font-size: 22rpx;
    min-width: 100rpx;
  }
  
  .toggle-text {
    font-size: 22rpx;
  }
  
  .input-actions-h5,
  .input-actions-bottom {
    gap: 6px;
  }
  
  .action-left,
  .action-right {
    gap: 6px;
  }
}

@media (min-width: 769px) {
  .deep-btn {
    font-size: 28rpx;
    padding: 10rpx 18rpx;
  }
  
  .deep-icon {
    font-size: 22rpx;
  }
  
  .deep-text {
    font-size: 26rpx;
  }
  
  .model-selector {
    font-size: 28rpx;
    padding: 10rpx 18rpx;
  }
  
  .model-text {
    font-size: 26rpx;
  }
  
  .model-arrow {
    font-size: 22rpx;
  }
  
  .deep-thinking-toggle {
    padding: 10rpx 18rpx;
    border-radius: 24rpx;
    font-size: 28rpx;
    min-width: 140rpx;
  }
  
  .toggle-text {
    font-size: 28rpx;
  }
}

/* 高级设置面板样式 */
.advanced-settings {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.settings-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.settings-close {
  font-size: 20px;
  color: #95a5a6;
  cursor: pointer;
  padding: 5px;
}

.settings-content {
  padding: 10px 0;
}

.setting-item {
  margin-bottom: 25px;
}

.setting-label {
  display: block;
  font-size: 14px;
  color: #495057;
  margin-bottom: 10px;
  font-weight: 500;
}

/* 小程序模式高级设置样式 */
@media (max-width: 480px) {
  .advanced-settings {
    padding: 16px;
    border-radius: 16px 16px 0 0;
  }
  
  .settings-title {
    font-size: 16px;
  }
  
  .setting-label {
    font-size: 13px;
  }
}
.send-btn {
  background: #6c5ce7;
  border: none;
  color: #fff;
  border-radius: 50%;
  font-size: 16px;
}
.model-selector {
  display: flex; /* 弹性布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 8rpx; /* 元素间距 */
  font-size: 26rpx; /* 字体大小 */
  color: #666; /* 文字颜色 */
  padding: 8rpx 16rpx; /* 内边距 */
  background: rgba(0, 0, 0, 0.05); /* 半透明背景 */
  border-radius: 12rpx; /* 圆角 */
  margin-right: 20rpx; /* 右侧外边距 */
}

/* 小程序模式模型选择器样式 */
.input-actions-bottom .model-selector {
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 10rpx;
  margin-right: 16rpx;
}
.separator {
  width: 0;
  height: 24px;
  border-left: 1px solid #e5e7eb;
  margin: 0 6px;
}

/* 小程序模式分隔符样式 */
.input-actions-bottom .separator {
  height: 20px;
  margin: 0 4px;
}

/* AI思考指示器样式（省略号） */
.thinking-indicator {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e9ecef;
  margin-bottom: 6px;
}

.thinking-dots {
  display: flex;
  align-items: center;
  gap: 2px;
}

.dot {
  font-size: 16px;
  color: #666;
  font-weight: 500;
  animation: dot-bounce 1.4s ease-in-out infinite;
}

.dot:nth-child(1) {
  animation-delay: 0s;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes dot-bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-6px);
  }
}

/* 打字机光标 */
@keyframes blink {
  0%, 49% { opacity: 1; }
  50%, 100% { opacity: 0; }
}
.cursor {
  display: inline-block;
  width: 8px;
  margin-left: 2px;
  animation: blink 1s step-end infinite;
  color: #6c5ce7;
}

/* 禁用状态的发送按钮 */
.send-btn[disabled] {
  opacity: 0.6;
}

/* 响应式断点样式 */
/* 平板断点 */
@media (min-width: 481px) {
  .chat-container {
    max-width: 720px;
    margin: 0 auto;
  }
  
  .question-input-h5 {
    max-width: 680px;
  }
  
  .input-actions-h5 {
    max-width: 680px;
  }
  
  .message-bubble {
    max-width: 80%;
  }
  
  /* 历史对话标题在小屏幕上的优化 */
  .history-title {
    max-width: 200px;
  }
  
  .history-content {
    max-width: calc(100% - 50px);
  }
}

/* 桌面中等断点 */
@media (min-width: 769px) {
  .chat-container {
    max-width: 820px;
    margin: 0 auto;
  }
  
  .question-input-h5 {
    max-width: 780px;
  }
  
  .input-actions-h5 {
    max-width: 780px;
  }
  
  .message-bubble {
    max-width: 70%;
  }
}

/* 桌面大屏断点 */
@media (min-width: 1025px) {
  .chat-container {
    max-width: 960px;
    margin: 0 auto;
  }
  
  .question-input-h5 {
    max-width: 920px;
  }
  
  .input-actions-h5 {
    max-width: 920px;
  }
  
  .message-bubble {
    max-width: 65%;
  }
}

.footer {
  width: 100%;
  max-width: 600px;
  margin: 24px auto 0 auto;
  padding: 16px 0 0 0;
  text-align: center;
  color: #adb5bd;
  font-size: 13px;
}
.footer-text {
  margin-bottom: 4px;
}
</style>